import datetime
import os
import time
import traceback
import random
import base64
import json

import requests
from loguru import logger
import numpy
import zipfile
import hashlib


class JD_BILL:
    def __init__(self, playwright, host, app_id):
        self.app_id = app_id
        self.secret = "P4I8HCOP1OP7432XZVKR2MPJKKVQ7J"
        self.playwright = playwright
        self.host = host
        self.context = None
        self.browser = None
        self.page = None
        self.index_url = "https://passport.jdpay.com/login/index.do"
        self.bill_download_path = os.path.join(os.getcwd(), 'jdBill')
        if not os.path.exists(self.bill_download_path):
            os.makedirs(self.bill_download_path)
        self.tj_account = self.get_tujian_account()

    def login(self, store):
        browser = self.playwright.chromium.launch(headless=False)
        self.context = browser.new_context(accept_downloads=True)
        self.page = self.context.new_page()
        self.page.goto(self.index_url, timeout=20000)
        # for i in range(5):
        #     logger.info(f'检查弹窗【{i+1}】秒...')
        #     if self.page.query_selector('div.step-close:visible') is not None and self.page.query_selector('div.step-close:visible').is_visible():
        #         self.page.query_selector('div.step-close:visible').click()
        #         break
        #     time.sleep(1)
        # self.page.query_selector('#loginbar >> a:has-text("登录")').click()
        self.wait(self.page)
        time.sleep(5)
        login_frame = self.page.frame(url='https://passport.jdpay.com/common/entry.do?*')
        login_frame.query_selector('#loginname').fill(store['userName'])
        login_frame.query_selector('#nloginpwd').fill(store['pwd'])
        time.sleep(1)
        logger.info('点击登录')
        login_frame.query_selector('#paipaiLoginSubmit').click()
        time.sleep(3)
        # 检查是否出现滑动验证码
        if login_frame.query_selector('div.JDJRV-suspend-slide') is not None and login_frame.query_selector('div.JDJRV-suspend-slide').is_visible():
            logger.info("出现滑动验证码，开始滑动...")
            code_path = os.path.join(os.getcwd(), 'code.png')
            for k in range(20):
                try:
                    if login_frame.query_selector('div.JDJRV-suspend-slide') is None:
                        break
                    login_frame.query_selector('div.JDJRV-bigimg').screenshot(path=code_path)
                    time.sleep(0.5)
                    dist = int(self.get_slider_xy(code_path))
                    box = login_frame.query_selector('div.JDJRV-slide-btn').bounding_box()
                    track = self.get_tracks(dist+20, 1, self.ease_out_quart)
                    ix = int(box['x'] + box['width'] // 2)
                    iy = int(box['y'] + box['height'] // 2)
                    self.page.mouse.move(ix, iy)
                    self.page.mouse.down(button='left')
                    self.move_to_gap(self.page, ix, iy, track)
                    time.sleep(1.5)
                    logger.info("滑动完成...")
                    time.sleep(5)
                except:
                    pass
        self.wait(self.page)
        # 处理短信验证码
        self.set_sms_code(store['mobile'])
        for i in range(20):
            try:
                if self.page.query_selector('a:has-text("商户中心")') is not None and self.page.query_selector('a:has-text("商户中心")').is_visible():
                    logger.info('登录成功')
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i+1}】秒...')
        return True, ''

    # 输入手机验证码
    def set_sms_code(self, mobile):
        has_sms = False
        for c in range(5):
            try:
                if self.page.query_selector('div.tip-btnbox:has-text("手机短信验证码"):visible') is not None:
                    has_sms = True
                    break
                logger.info(f'正在检查是否需要手机验证码【{c + 1}】秒')
            except:
                pass
            time.sleep(1)
        logger.info(f'检查结果：【{has_sms}】')
        if has_sms:
            self.page.query_selector('div.tip-btnbox:has-text("手机短信验证码"):visible').click()
            time.sleep(1)
            self.page.query_selector('button.btn-msg').click()
            time.sleep(30)
            sms_text = self.get_sms_code(mobile)
            if '京东' not in sms_text:
                logger.info('获取验证码失败')
                raise Exception('获取验证码失败')
            # 验证码示例：【京东】验证码：123456，您正在新设备上登录。请确认本人操作，切勿泄露给他人，京东工作人员不会索取此验证码。
            sms_code = sms_text.split('：')[1].split('，')[0]
            self.page.query_selector('input[placeholder="请输入手机验证码"]').fill(sms_code)
            time.sleep(1)
            self.page.query_selector('button:has-text("提交认证")').click()

    # 获取手机验证码
    def get_sms_code(self, mobile):
        for t in range(3):
            try:
                res = requests.get(f'http://1.95.166.150:8997/api/v1/sms/info/{mobile}')
                logger.info(f'获取手机验证码结果：{res.text}')
                sms_text = res.json()['data']
                if sms_text is not None and '京东' in sms_text:
                    return sms_text
                time.sleep(3)
            except:
                logger.info(traceback.format_exc())
        return ''

    def ease_out_quart(self, x):
        return 1 - pow(1 - x, 4)

    def get_tracks(self, distance, seconds, ease_func):
        distance += 0
        tracks = [0]
        offsets = [0]
        for t in numpy.arange(0.0, seconds, 0.1):
            ease = ease_func
            offset = round(ease(t / seconds) * distance)
            tracks.append(offset - offsets[-1])
            offsets.append(offset)
        tracks.extend([-3, -2, -3, -2, -2, -2, -2, -1, -0, -1, -1, -1])
        return tracks

    def move_to_gap(self, page, ix, iy, track):
        """
        慢速移动鼠标
        :param ix:
        :param iy:
        :param track:
        :return:
        """
        f_y = [10, 12, 4, 6, 8, -4, -6, -8]
        t_list = [0.1, 0.2, 0.3, 0.4, 0.5]
        mx = ix
        while track:
            x = track.pop(0)
            mx = mx + x
            page.mouse.move(mx, iy + random.choice(f_y))
            time.sleep(random.choice(t_list))
        time.sleep(1)
        page.mouse.up()

    def get_slider_xy(self, backImgPath):
        api = 'http://api.ttshitu.com/base64'
        with open(backImgPath, 'rb') as f:
            base64_data = base64.b64encode(f.read())
            b642 = base64_data.decode()
        params = {"typeid": "33", "image": b642, "username": self.tj_account['tjName'], "password": self.tj_account['tjPass']}
        headers = {'content-type': 'application/json;charset=UTF-8'}
        result = json.loads(requests.post(api, json=params, headers=headers).text)
        if result['success']:
            return result["data"]["result"]
        else:
            logger.info(result["message"])
            return result["data"]

    def download_bill_file(self, store, str_last_month):
        self.page.goto("https://ims.jdpay.com/layout/frame.do?callBackUrl=/fundapp/accountquery/toAccountBalance.do")
        logger.info('跳转到【资金账户】页面...')
        self.wait(self.page)
        for i in range(20):
            try:
                if self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")') is not None and self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i+1}】秒...')
        logger.info('点击【商户结算】...')
        self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")').click()
        time.sleep(1)
        logger.info('点击【月账单】...')
        self.page.query_selector('#monthlyBill').click()
        self.wait(self.page)
        for i in range(20):
            try:
                if self.page.query_selector('#searchform') is not None and self.page.query_selector('#searchform').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i+1}】秒...')
        logger.info('选择【账户代码】')
        self.page.query_selector('div.ui-sel-div').click()
        time.sleep(1)
        self.page.query_selector('input.filterinput').fill(store['account'])
        time.sleep(1)
        # 选择第一个
        if len(self.page.query_selector_all('#accountList >> li')) == 0:
            logger.info(f'按照店铺标识【{store["account"]}】找不到账户')
            return None, None
        self.page.query_selector('#accountList >> li >> nth=0').click()
        logger.info('选择【时间范围】')
        last_month = datetime.datetime.strptime(str_last_month + '-01', '%Y-%m-%d')
        # 修改开始月份
        self.change_month('#container1', last_month)
        time.sleep(1)
        # 修改结束月份
        self.change_month('#container2', last_month)
        logger.info('点击【查询】...')
        with self.page.expect_response('https://ims.jdpay.com/capital/getMonthlyBillList.do') as response_info:
            self.page.query_selector('a:text-is("查询")').click()
        response = response_info.value
        self.wait(self.page)
        if response.status == 200:
            total = len(response.json()['rows'])
            if total > 0:
                logger.info(f'查询到【{total}】条数据...')
            else:
                logger.info('暂无数据')
                return None, 1
        else:
            logger.info('查询失败')
            raise Exception("查询失败")
        with self.page.expect_download() as download_info:
            self.page.query_selector('a:has-text("下载商城订单明细")').click()
        download_obj = download_info.value
        file_path = os.path.join(self.bill_download_path, f'jdBill-{store["platformStoreName"]}-{str_last_month}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.zip')
        # 删除旧文件
        if os.path.exists(file_path):
            os.remove(file_path)
        download_obj.save_as(file_path)
        # 等待文件下载完成
        for i in range(60):
            if os.path.exists(file_path):
                break
            time.sleep(1)
        if not os.path.exists(file_path):
            raise Exception(f"【{file_path}】下载失败")
        logger.info(f"【{file_path}】下载成功")
        bill_path = self.get_bill_file(file_path, last_month.strftime("%Y%m"))
        logger.info(f'京东结算单文件路径：{bill_path}')
        return bill_path, 1

    def get_bill_count(self, store, str_last_month):
        self.page.goto("https://ims.jdpay.com/layout/frame.do?callBackUrl=/fundapp/accountquery/toAccountBalance.do")
        logger.info('跳转到【资金账户】页面...')
        self.wait(self.page)
        for i in range(20):
            try:
                if self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")') is not None and self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i + 1}】秒...')
        logger.info('点击【商户结算】...')
        self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")').click()
        time.sleep(1)
        logger.info('点击【月账单】...')
        self.page.query_selector('#monthlyBill').click()
        self.wait(self.page)
        for i in range(20):
            try:
                if self.page.query_selector('#searchform') is not None and self.page.query_selector('#searchform').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i + 1}】秒...')
        logger.info('选择【账户代码】')
        self.page.query_selector('div.ui-sel-div').click()
        time.sleep(1)
        self.page.query_selector('input.filterinput').fill(store['account'])
        time.sleep(1)
        # 选择第一个
        if len(self.page.query_selector_all('#accountList >> li')) == 0:
            logger.info(f'按照店铺标识【{store["account"]}】找不到账户')
            return None
        self.page.query_selector('#accountList >> li >> nth=0').click()
        logger.info('选择【时间范围】')
        last_month = datetime.datetime.strptime(str_last_month + '-01', '%Y-%m-%d')
        # 修改开始月份
        self.change_month('#container1', last_month)
        time.sleep(1)
        # 修改结束月份
        self.change_month('#container2', last_month)
        logger.info('点击【查询】...')
        with self.page.expect_response('https://ims.jdpay.com/capital/getMonthlyBillList.do') as response_info:
            self.page.query_selector('a:text-is("查询")').click()
        response = response_info.value
        self.wait(self.page)
        if response.status == 200:
            total = len(response.json()['rows'])
            if total > 0:
                return f'收入：{response.json()["rows"][0]["totalDebitAmt"]}，支出：{response.json()["rows"][0]["totalCreditAmt"]}'
            return '收入：0，支出：0'
        else:
            logger.info('查询失败')
            raise Exception("查询失败")

    def get_bill_file(self, file_path, last_month):
        # 删除旧文件
        path = os.path.join(self.bill_download_path, last_month)
        file_list = []
        self.get_all_files(path, file_list)
        for file in file_list:
            os.remove(file)
        # 解压文件
        self.unzip(file_path, path)
        # 解压第二层压缩包
        bill_path = None
        for file in os.listdir(path):
            if file.endswith('.zip'):
                bill_path = os.path.join(path, file.rsplit('.')[0])
                if not os.path.exists(bill_path):
                    os.makedirs(bill_path)
                # 解压文件
                self.unzip(os.path.join(path, file), bill_path)
                break
        if os.path.exists(bill_path):
            for file in os.listdir(bill_path):
                return os.path.join(bill_path, file)
        else:
            return None

    def get_all_files(self, path, file_list):
        if not os.path.exists(path):
            return
        for file in os.listdir(path):
            if os.path.isfile(os.path.join(path, file)):
                file_list.append(os.path.join(path, file))
            else:
                self.get_all_files(os.path.join(path, file), file_list)

    def change_month(self, id, last_month):
        self.page.query_selector(id).click()
        time.sleep(1)
        frame = self.page.frame(url='about:blank')
        # 选择月份
        frame.query_selector('input.yminput >> nth=0').click()
        time.sleep(1)
        # 输入上个月
        frame.query_selector('input.yminputfocus').fill(str(last_month.month))
        time.sleep(1)
        self.page.keyboard.press("Escape")
        # 选择年份
        frame.query_selector('input.yminput >> nth=1').click()
        time.sleep(1)
        frame.query_selector('input.yminputfocus').fill(str(last_month.year))
        time.sleep(1)
        self.page.keyboard.press("Escape")
        time.sleep(1)
        frame.query_selector('#dpOkInput').click()
        time.sleep(1)

    def get_store_account(self, platform, type):
        timestamp = int(time.time() * 1000)
        text = "{}{}{}".format(self.app_id, timestamp, self.secret)
        sign = hashlib.md5(text.encode(encoding='UTF-8')).hexdigest()
        url = self.host + f"api/v1/storeAccount/getAccountList/{platform}?appId={self.app_id}&type={type}&sign={sign.upper()}&timestamp={timestamp}"
        logger.info(url)
        res = requests.get(url)
        logger.info(f'获取店铺账号结果：{res.text}')
        if res.status_code == 200:
            return res.json()['data']

    # 获取图鉴账号密码
    def get_tujian_account(self):
        timestamp = int(time.time() * 1000)
        text = "{}{}{}".format(self.app_id, timestamp, self.secret)
        sign = hashlib.md5(text.encode(encoding='UTF-8')).hexdigest()
        url = self.host + f"api/v1/tjAccount/findOne?appId={self.app_id}&sign={sign.upper()}&timestamp={timestamp}"
        res = requests.get(url)
        if res.status_code == 200:
            return res.json()['data']

    def wait(self, page, seconds=1):
        try:
            page.wait_for_load_state(state="domcontentloaded")
            time.sleep(seconds)
        except:
            pass

    def upload_file(self, api_url, coding_param, file_list):
        try:
            timestamp = int(time.time() * 1000)
            text = "{}{}{}".format(self.app_id, timestamp, self.secret)
            sign = hashlib.md5(text.encode(encoding='UTF-8')).hexdigest()
            logger.info("正在上传文件到服务器")
            url = self.host + api_url + f"?appId={self.app_id}&sign={sign.upper()}&timestamp={timestamp}"
            files = []
            for file in file_list:
                files.append(('file', (open(file, 'rb'))))
            logger.info(f'上传文件到服务器url：{url}')
            response = requests.request("POST", url, files=files, headers={'codingParam': coding_param}, timeout=180)
            logger.info('上传文件到服务器结果：' + response.text)
        except:
            logger.info(traceback.format_exc())

    def encode_param(self, data_list):
        timestamp = int(time.time() * 1000)
        text = "{}{}{}".format(self.app_id, timestamp, self.secret)
        sign = hashlib.md5(text.encode(encoding='UTF-8')).hexdigest()
        url = self.host + f"api/v1/storeAccount/codingParams?appId={self.app_id}&sign={sign.upper()}&timestamp={timestamp}"
        res = requests.post(url, data=json.dumps(data_list), headers={'content-type': 'application/json'})
        if res.status_code == 200:
            return res.json()['data']

    def close(self):
        try:
            if self.page:
                self.page.close()
        except:
            pass
        try:
            if self.browser:
                self.browser.close()
        except:
            pass
        try:
            if self.context:
                self.context.close()
        except:
            pass

    def download_fund_flow(self, store, strYesterday):
        self.page.goto("https://ims.jdpay.com/layout/frame.do?callBackUrl=/fundapp/accountquery/toAccountBalance.do")
        logger.info('跳转到【资金账户】页面...')
        self.wait(self.page)
        for i in range(20):
            try:
                if self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")') is not None and self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i + 1}】秒...')
        logger.info('点击【账户流水】...')
        self.page.query_selector('#capitalLeftMenu >> li:has-text("账户流水")').click()
        time.sleep(1)
        logger.info('点击【账单查询】...')
        self.page.query_selector('#aiaccount').click()
        self.wait(self.page)
        for i in range(20):
            try:
                if self.page.query_selector('#dataList') is not None and self.page.query_selector('#dataList').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i + 1}】秒...')
        logger.info('选择【账户】')
        self.page.query_selector('#accountTypeSelectDiv').click()
        time.sleep(1)
        self.page.query_selector('#accountInputSearch').fill(store['account'])
        time.sleep(1)
        # 选择第一个
        if len(self.page.query_selector_all('#accountTypeOptions >> li')) == 0:
            logger.info(f'按照店铺标识【{store["account"]}】找不到账户')
            return None, None
        self.page.query_selector('#accountTypeOptions >> li >> nth=0').click()
        logger.info('选择【月份】')
        # 昨天对应的月份
        yesterday = datetime.datetime.strptime(strYesterday, '%Y-%m-%d')
        self.page.query_selector('#timeTypeSelectDiv').click()
        time.sleep(1)
        self.page.query_selector(f'#timeTypeOptions >> a[id="{yesterday.strftime("%Y-%m")}"]').click()
        time.sleep(1)
        logger.info('点击【查询】...')
        with self.page.expect_response('https://ims.jdpay.com/aiaccount/accountData.do?*') as response_info:
            self.page.query_selector('a:text-is("查询")').click()
        response = response_info.value
        self.wait(self.page)
        logger.info(response.json())
        if response.status == 200:
            total = response.json()['total']
            if total > 0:
                logger.info(f'查询到【{total}】条数据...')
            else:
                logger.info('暂无数据')
                return None, 1
        else:
            logger.info('暂无数据')
            return None, 1
        if self.page.query_selector(f'table.table-gai >> tbody >> tr:has(td:has-text("{yesterday.strftime("%Y-%m-%d")}")) >> a:has-text("账单下载")') is None:
            logger.info('暂无数据')
            return None, 1
        self.page.query_selector(f'table.table-gai >> tbody >> tr:has(td:has-text("{yesterday.strftime("%Y-%m-%d")}")) >> a:has-text("账单下载")').click()
        time.sleep(2)
        logger.info('点击【去下载列表】')
        self.page.query_selector('a:has-text("去【下载列表】")').click()
        self.wait(self.page)
        # 根据账单日期找到对应的报表
        for i in range(20):
            try:
                if self.page.query_selector('#accountAggregateLi') is not None and self.page.query_selector('#accountAggregateLi').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i + 1}】秒...')
        time.sleep(1)
        self.page.query_selector('#accountTypeSelectDiv').click()
        time.sleep(1)
        self.page.query_selector('#accountInputSearch').fill(store["account"])
        time.sleep(1)
        # 选择第一个
        self.page.query_selector('#accountTypeOptions >> li >> nth=0').click()
        with self.page.expect_response('https://ims.jdpay.com/aidownload/fileData.do?*') as response_info:
            self.page.query_selector('a:text-is("查询")').click()
        response = response_info.value
        self.wait(self.page)
        tr_list = self.page.query_selector_all('table.table-gai >> tbody >> tr')
        tr_index = -1
        for index, tr in enumerate(tr_list):
            bill_time = tr.query_selector('td >> nth=2').text_content()
            status = tr.query_selector('td >> nth=3').text_content()
            logger.info(f'账单日期：{bill_time}，状态：{status}')
            if bill_time.strip() == yesterday.strftime("%Y-%m-%d") and status == '处理成功':
                tr_index = index
                break
        if tr_index == -1:
            raise Exception('账单下载失败')
        self.page.query_selector(f'table.table-gai >> tbody >> tr >> nth={tr_index} >> a:has-text("查看文件")').click()
        time.sleep(2)
        with self.page.expect_download() as download_info:
            self.page.query_selector(f'div.layui-layer-content >> a:has-text("立即下载")').click()
        download_obj = download_info.value
        filename = self.page.query_selector('div.layui-layer-content >> #dataList >> table >> tbody >> tr >> nth=0 >> td').text_content()
        is_zip = True
        if filename.lower().endswith('.zip'):
            file_path = os.path.join(self.bill_download_path, f'jdFundFlow-{store["platformStoreName"]}-{strYesterday.replace("-", "")}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.zip')
        elif filename.lower().endswith('.csv'):
            file_path = os.path.join(self.bill_download_path, f'jdFundFlow-{store["platformStoreName"]}-{strYesterday.replace("-", "")}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.csv')
            is_zip = False
        # 删除旧文件
        if os.path.exists(file_path):
            os.remove(file_path)
        download_obj.save_as(file_path)
        # 等待文件下载完成
        for i in range(60):
            if os.path.exists(file_path):
                break
            time.sleep(1)
        if not os.path.exists(file_path):
            raise Exception(f"【{file_path}】下载失败")
        logger.info(f"【{file_path}】下载成功")
        time.sleep(1)
        if is_zip:
            fund_flow_path = self.get_fund_flow_file(file_path, strYesterday)
        else:
            fund_flow_path = file_path
        logger.info(f'京东资金流水文件路径：{fund_flow_path}')
        return fund_flow_path, 1

    def get_fund_flow_count(self, store, str_last_month):
        self.page.goto("https://ims.jdpay.com/layout/frame.do?callBackUrl=/fundapp/accountquery/toAccountBalance.do")
        logger.info('跳转到【资金账户】页面...')
        self.wait(self.page)
        for i in range(20):
            try:
                if self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")') is not None and self.page.query_selector('#capitalLeftMenu >> li:has-text("商户结算")').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i + 1}】秒...')
        logger.info('点击【账户流水】...')
        self.page.query_selector('#capitalLeftMenu >> li:has-text("账户流水")').click()
        time.sleep(1)
        logger.info('点击【账单查询】...')
        self.page.query_selector('#aiaccount').click()
        self.wait(self.page)
        for i in range(20):
            try:
                if self.page.query_selector('#dataList') is not None and self.page.query_selector('#dataList').is_visible():
                    break
            except:
                pass
            time.sleep(1)
            logger.info(f'等待页面加载【{i + 1}】秒...')
        logger.info('选择【账户】')
        self.page.query_selector('#accountTypeSelectDiv').click()
        time.sleep(1)
        self.page.query_selector('#accountInputSearch').fill(store['account'])
        time.sleep(1)
        # 选择第一个
        if len(self.page.query_selector_all('#accountTypeOptions >> li')) == 0:
            logger.info(f'按照店铺标识【{store["account"]}】找不到账户')
            return None
        self.page.query_selector('#accountTypeOptions >> li >> nth=0').click()
        logger.info('选择【月账单】')
        self.page.query_selector('#monthBill').click()
        time.sleep(1)
        logger.info('选择年份')
        self.page.query_selector('#timeTypeSelectDiv').click()
        time.sleep(1)
        year = str_last_month.split('-')[0]
        self.page.query_selector(f'#timeTypeOptions >> a[id="{year}"]').click()
        # 昨天对应的月份
        time.sleep(1)
        logger.info('点击【查询】...')
        with self.page.expect_response('https://ims.jdpay.com/aiaccount/accountData.do?*') as response_info:
            self.page.query_selector('a:text-is("查询")').click()
        response = response_info.value
        self.wait(self.page)
        if response.status == 200:
            total = response.json()['total']
            if total > 0:
                filter_list = list(filter(lambda x: x['statDate'].startswith(str_last_month), response.json()['rows']))
                if len(filter_list) > 0:
                    return filter_list[0]['inCount']+filter_list[0]['outCount']
                else:
                    return 0
            else:
                return 0
        else:
            raise Exception('查询失败')

    def unzip(self, zip_path, extract_path):
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(extract_path)

    def get_fund_flow_file(self, file_path, yesterday):
        # 删除旧文件
        path = os.path.join(self.bill_download_path, yesterday)
        file_list = []
        self.get_all_files(path, file_list)
        for file in file_list:
            os.remove(file)
        # 解压文件
        self.unzip(file_path, path)
        for file in os.listdir(path):
            if '_jdsc' not in file:
                return os.path.join(path, file)
        return None

    # 更新日志
    def update_log(self, log_id_list, message):
        data = {'logIdList': log_id_list, 'message': message}
        timestamp = int(time.time() * 1000)
        text = "{}{}{}".format(self.app_id, timestamp, self.secret)
        sign = hashlib.md5(text.encode(encoding='UTF-8')).hexdigest()
        url = self.host + f"api/v1/logRecord/updateLog?appId={self.app_id}&sign={sign.upper()}&timestamp={timestamp}"
        logger.info(f'url：{url}')
        logger.info(f'保存参数：{data}')
        res = requests.post(url, json=data)
        logger.info(f'保存结果：{res.text}')
        if res.status_code == 200:
            return res.json()['data']